#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

long total_size = 0;  // 改为long类型，防止大文件溢出
int count = 0;

void getName(char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *dent;
    while ((dent = readdir(dir)) != NULL) {
        if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) {
            continue;
        }

        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, dent->d_name);

        if (dent->d_type == DT_DIR) {
            getName(full_path);  // 递归处理子目录
        } else {
            if (strcmp(dent->d_name, "1.txt") == 0) {
                count++;
                
                // 获取文件大小
                struct stat file_stat;
                if (stat(full_path, &file_stat) == 0) {
                    total_size += file_stat.st_size;
                    printf("Found: %s (Size: %ld bytes)\n", full_path, file_stat.st_size);
                } else {
                    perror("stat");
                }
            }
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[]) {
    char *start_path = (argc > 1) ? argv[1] : ".";
    getName(start_path);
    
    printf("\n统计结果:\n");
    printf("找到的1.txt文件总数: %d\n", count);
    printf("所有'1.txt'文件总大小为 : %ld bytes\n", total_size);
    
    return 0;
}
